import mmpx from '@/psoon/pub/px2mm'
import "./rect.scss"

class Rect{

  _rect_resize_o = null

  elEvents ={
    'mousedown @ .rect.bar.r,.rect.bar.b': '_initRectMouseEvents' 
  }

  init(){
    console.log('rect init')
  }

  onRendered () {
    $(this.el).append(`<div class='rect-cls rect l' style='position:absolute;width:1px;height:100%;background:#777;left:0;top:0;'><div>`)
    $(this.el).append(`<div class='rect-cls rect r' style='position:absolute;width:1px;height:100%;background:#777;right:0;top:0;'><div>`)
    $(this.el).append(`<div class='rect-cls rect t' style='position:absolute;width:100%;height:1px;background:#777;left:0;top:0;'><div>`)
    $(this.el).append(`<div class='rect-cls rect b' style='position:absolute;width:100%;height:1px;background:#777;left:0;bottom:0;'><div>`)
    $(this.el).append(`<div class='rect-cls rect bar b' style='position:absolute;left:50%;bottom:-4px;margin-left:-4px;'><div>`)
    $(this.el).append(`<div class='rect-cls rect bar r' style='position:absolute;right:-4px;top:50%;margin-top:-4px;'><div>`)
  }

  _initRectMouseEvents(e){
    const el = e.target
    const direct = $(el).hasClass('r') ? 'w' : ($(el).hasClass('b') ? 'h' : '')
    const o = this._rect_resize_o
    const thatel = this.el
    if(!thatel) return
    if( e.type === 'mousedown'){
      this._rect_resize_o  = {
        start: {
          sz: { w: thatel.offsetWidth, h: thatel.offsetHeight},
          e: e,
          x:e.clientX, 
          y:e.clientY
        }
      }
      this._rect_resize_o.t = direct

      window.onmousemove = e=>{
        const o = this._rect_resize_o
        if(o && o.t === 'w'){
          const to = o.start.sz.w + (e.clientX - o.start.x)
          if(to>0){
            $(thatel).css({width: mmpx.getNumber(to, 'mm') + 'mm'})
          }
        }else if(o && o.t === 'h'){
          const to = o.start.sz.h + (e.clientY - o.start.y)
          if(to>0){
            $(thatel).css({height: mmpx.getNumber(to, 'mm') + 'mm'})
          }
        }
      }
      window.onmouseup = e=>{
        this._rect_resize_o = null
        window.onmousemove = null
        window.onmouseup = null
      }
    }
  }

  rect(){
    console.log('is rect')
  }
}

export default Rect